import random
import uuid

from flask import current_app, request, render_template, g, abort, url_for
from flask.json import jsonify

from info import constants, db
from info.models import Goods, Category, Shop_cart
from info.utils.aplipay import AliPay
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import goods_blu


@goods_blu.route('/commodity', methods=['GET', 'POST'])
@user_login_data
def commodity():
    """商品列表"""
    user = g.user
    goods = ''
    try:
        goods_list = Goods.query.order_by(Goods.g_id.desc()).limit(constants.ADMIN_NEWS_PAGE_MAX_COUNT)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败!')

    click_goods_list = []
    # 编列所有新闻 把里面的新闻对象转为字典
    for goods in goods_list:
        click_goods_list.append(goods.to_dict())
    # print(click_goods_list)

    # 3.1获取所有分类
    try:
        categories = Category.query.filter(Category.c_id <= 8).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败!')

    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())

    if user:
        try:
            shop_car = Shop_cart.query.filter(Shop_cart.c_user_id == user.u_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="购物车为空")
    else:
        shop_car = None
    data = {
        "user_info": user.to_dict() if user else None,
        'click_goods_list': click_goods_list,
        'category_list': categories_list,
        'shop_car': shop_car,

    }
    return render_template('index/liebiaoye.html', data=data)


@goods_blu.route('/commoditylist')
def get_commodity_list():
    # 获取参数
    # 1. 获取参数
    cid = request.args.get('cid', 1)  # 分类id
    page = request.args.get('page', 1)  # 第几页
    per_page = request.args.get('per_page', 10)  # 每页的数量

    # 2. 校验参数
    try:
        page = int(page)
        per_page = int(per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = []
    if cid != 0:
        # 3. 查询数据 分页
        filters.append(Goods.category_id == cid)

    try:
        # *filters解包
        pagination = Goods.query.filter(*filters).order_by(Goods.create_time.desc()).paginate(page, per_page, False)
        # if cid == 0:
        #     # 获取查询出来的数据
        #     goods_list = Goods.query.order_by(Goods.g_id.desc()).limit(50)

        # else:
        goods_list = pagination.items
        # 获取到总页数
        total_page = pagination.pages
        # 当前页对象
        current_page = pagination.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    goods_li = []

    for goods in goods_list:
        goods_li.append(goods.to_dict())

    ret = {
        "errno": RET.OK,
        "errmsg": "OK",
        "totalPage": total_page,
        "currentPage": current_page,
        "goodsList": goods_li,
        "cid": cid
    }
    return jsonify(ret)


@goods_blu.route('/<int:goods_id>', methods=['GET', 'POST'])
@user_login_data
def goods_detail(goods_id):
    """商品详情页"""

    # 从g变量取出user对象
    user = g.user

    goods = None
    # 1111获取新闻详情数据
    try:
        goods = Goods.query.get(goods_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not goods:
        # 商品数据没有找到
        abort(404)

    # 444 当前新闻是否已经收藏
    # 设置变量 表示是否收藏 默认为false
    is_collected = False
    if user:
        # 如果当前在用户的收藏列表里 设置is_collected True
        if goods in user.collection_goods:
            is_collected = True

    if user:
        try:
            shop_car = Shop_cart.query.filter(Shop_cart.c_user_id == user.u_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="购物车为空")
    else:
        shop_car = None
    data = {
        "goods": goods,  # 当前商品
        "is_collected": is_collected,  # 是否被收藏
        "user_info": user.to_dict() if user else None,  # 是否登录
        "shop_car": shop_car,
    }
    return render_template('index/xiangqingye.html', data=data)


@goods_blu.route('/goods_collect', methods=['POST'])
@user_login_data
def goods_collect():
    """商品收藏和取消收藏
    1接受参数
    2 校验
    3查询新闻数据
    4收藏或者取消收藏
    5返回响应
    """
    user = g.user

    # 11获取传来的json数据
    json_data = request.json
    goods_id = json_data.get('goods_id')
    action = json_data.get('action')

    # 2校验
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if not goods_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("collect", "cancel_collect"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3查询商品数据
    try:
        goods = Goods.query.get(goods_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not goods:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")

    # 4收藏或者取消收藏
    if action == "collect":
        user.collection_goods.append(goods)
    else:
        user.collection_goods.remove(goods)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@goods_blu.route('/shop_car', methods=['POST'])
@user_login_data
def shop_car():
    """加入购物车"""

    user = g.user

    # 11获取传来的json数据
    json_data = request.json
    goods_id = json_data.get('goods_id')  # 商品id
    goods_count = json_data.get('goods_count')  # 商品数量
    goods_count = int(goods_count)
    # 2校验
    if not user:
        return jsonify(errno='8181', errmsg="请登录")

    if not goods_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3查询商品数据
    try:
        goods = Goods.query.get(goods_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not goods:
        return jsonify(errno=RET.NODATA, errmsg="商品数据不存在")

    if goods_count > goods.inventory:
        return jsonify(errno=RET.PARAMERR, errmsg='库存不够')

    try:
        shop_car = Shop_cart.query.filter(Shop_cart.c_user_id == user.u_id).one()
    except Exception as e:
        shop_car = Shop_cart()
        shop_car.c_user_id = user.u_id

    # 保存修改
    try:
        db.session.add(shop_car)
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    for good in shop_car.shop_goods:
        if goods == good:
            return jsonify(errno=RET.DBERR, errmsg='已加入购物车')
    try:
        shop_car.shop_goods.append(goods)
    except:
        return jsonify(errno=RET.DBERR, errmsg='加入购物车失败')
    # print('-----------加入后', shop_car.shop_goods)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="添加成功")


@goods_blu.route('/order')
@user_login_data
def order():
    # 从g变量取出user对象
    user = g.user
    if not user:
        return render_template('./index/login.html')

    g_id = request.args.get('g_id')
    g_count = request.args.get('g_count')

    goods = None
    try:
        goods = Goods.query.filter(Goods.g_id == g_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='没有该商品')
    goods_all_price = int(g_count) * int(goods.g_price)

    default_addr = None
    for addr in user.rece_list:
        default_addr = addr
    if not default_addr:
        data = {
            'base_user_info': user.to_dict()
        }
        return render_template('./index/dizhiguanli.html', data=data)

    data = {
        'goods': goods.to_dict(),
        'goods_count': g_count,
        'goods_all_price': goods_all_price,
        'user_addr': default_addr,
    }

    return render_template('./index/tianxieheduigouwuxinxi.html', data=data)


@goods_blu.route('/sousuo', methods=['POST', 'GET'])
def ss():
    """搜索"""
    # 获取参数
    a = request.json
    content = a.get('content')
    return jsonify(errno=RET.OK, errmsg='OK', content=content)


@goods_blu.route('/sousuo01', methods=['POST', 'GET'])
def liebiao():
    """搜索后显示的页面"""
    # 获取参数
    # print(111)
    p = request.args.get('p')
    # print(p)

    goods = ''
    try:
        goods = Goods.query.filter(Goods.g_name.like('%' + p + '%')).all()
        # print(goods)
    except Exception as e:
        current_app.logger.error(e)

    goods_list = []
    for good in goods:
        goods_list.append(good.to_dict())

    return render_template('index/jinrudianpuxiangqing.html', data=goods_list)


@goods_blu.route('/tijiaodingdan', methods=['POST', 'GET'])
@user_login_data
def tijiaodingdan():
    """提交订单"""

    # 获取参数
    user = g.user
    if not user:
        return render_template('./index/login.html')
    print("--------------------1----------------")
    money = request.json.get("money")
    print("----------------error----------------")
    try:
        money = int(money)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='价格信息错误')
    # money = 6

    # zfpwd01 = params.get('zfpwd01')

    # 传递参数初始化支付类
    alipay = AliPay(
        appid="2016101700706205",  # 设置签约的appid
        app_notify_url="http://projectsedus.com/",  # 异步支付通知url
        app_private_key_path=u"V:/web项目/flask/mi_shop0/info/utils/y_s.txt",  # 设置应用私钥
        alipay_public_key_path=u"V:/web项目/flask/mi_shop0/info/utils/zhi_g.txt",  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        debug=True,  # 默认False,                                   # 设置是否是沙箱环境，True是沙箱环境
        return_url="http://127.0.0.1:5000/goods/zhifuchenggong"  # 同步支付通知url
    )
    print("--------------------2--------------------")
    # 传递参数执行支付类里的direct_pay方法，返回签名后的支付参数，
    url = alipay.direct_pay(
        subject="测试订单",  # 订单名称
        # 订单号生成，一般是当前时间(精确到秒)+用户ID+随机数
        out_trade_no=str(uuid.uuid1()),  # 订单号
        total_amount=money,  # 支付金额
        return_url="http://127.0.0.1:5000/goods/zhifuchenggong"  # 支付成功后，跳转url
    )
    print("--------------------3----------------------")
    # 将前面后的支付参数，拼接到支付网关
    # 注意：下面支付网关是沙箱环境，
    re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
    # print(re_url)

    # 最终进行签名后组合成支付宝的url请求

    # 2. 校验参数
    # if not zfpwd01:
    #     return jsonify(errno=RET.PARAMERR, errmsg="请输入支付密码")
    # 3. 校验密码是否正确
    # if user.zfmm_password != zfpwd01:
    #     return jsonify(errno=RET.PWDERR, errmsg="支付密码错误")
    # 5返回相应
    return jsonify(errno=RET.OK, re_url=re_url)


@goods_blu.route('/zhifuchenggong', methods=['POST', 'GET'])
def zfcg():
    # 支付成功
    return '支付成功!'
